
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  ** This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * COPYRIGHT(c) 2020 STMicroelectronics
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_hal.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* USER CODE BEGIN Includes */

#include "oled.h"
#include "bmp280.h"
#include "ws2812b.h"
#include "ap3216.h"
#include "mpu6050.h"
#include "math.h"
#include "vl53l0x_a.h"
#include "vl53l0x_b.h"
#include "bluetooth.h"
#include "beep.h"

/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/

extern uint8_t RxByte;
extern uint8_t RxBuff[RxMax];

extern uint8_t colorR, colorG, colorB;
extern uint8_t colorR_Start, colorG_Start, colorB_Start;
extern uint8_t colorR_End, colorG_End, colorB_End;

extern uint8_t lightness;

const uint8_t ACCEL_RH_RECORD_NUM = 30;
const uint8_t LIGHTNESS_RECORD_NUM = 30;

uint8_t  MINIUM_LIGHTNESS    = 0x37;
uint16_t ACCEL_RH_THRESHOLD  = 500;
uint8_t  DOOR_OPEN_THRESHOLD = 100;
uint8_t  s                   = 0;
uint8_t  OPEN                = 0;
uint8_t  performed           = 0;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_NVIC_Init(void);

/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
void BMP_show(void);
void AP3212_show(void);
void MPU_show(void);
void VL_show(void);
void Door_Open(void);
void Door_Close(void);
uint16_t FLASH_Read(uint8_t offset);
void FLASH_Write(uint8_t offset, uint16_t Flash_Val);
void Flash_start(void);

/* USER CODE END PFP */

/* USER CODE BEGIN 0 */


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  *
  * @retval None
  */
int main(void)
{
  /* USER CODE BEGIN 1 */


  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART1_UART_Init();
  MX_TIM2_Init();

  /* Initialize interrupts */
  MX_NVIC_Init();
  /* USER CODE BEGIN 2 */

  HAL_Delay(10);
  
  BEEP_Init();
  for(uint8_t i=0;i<25;i++) {
    HAL_Delay(200);
    HAL_GPIO_TogglePin(led_GPIO_Port, led_Pin);
  }
  BEEP_Alarm(450);
  BEEP_Alarm(350);
  BEEP_Alarm(280);
  BEEP_Alarm(280);

  Flash_start();
  OLED_Init();
  BMP280_Init();
  AP3216_Init();
  MPU6050_Init();
  VL53L0X_A_Init();
  VL53L0X_B_Init();
  BLUETOOTH_Init();
  WS2812B_Init();

  HAL_UART_Receive_IT(&huart1, &RxByte, 1);

  OLED_ShowString(0, 0, (uint8_t *)"TMP:      PR:");
  OLED_ShowString(0, 1, (uint8_t *)"A-X:      ALS:-----");
  OLED_ShowString(0, 2, (uint8_t *)"A-Y:      DIS:-------");
  OLED_ShowString(0, 3, (uint8_t *)"A-Z:      ARH:-----");

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {

  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

    // Refresh every 4s
    if (!(s % 40)) {
      // Show BMP
      BMP_show();
    }
    // Show ALS
    AP3212_show();
    //Show ACCEL
    MPU_show();
    // Show Distance
    VL_show();
    // Update Light
    if (OPEN & !performed) {
      Door_Open();
      performed = 1;
    } else if (!OPEN & performed) {
      Door_Close();
      performed = 0;
      s = 0;
    } else if (!OPEN & !performed) {
      if (!(s % 40)) {
        WS2812B_Update();
      }
    }

    BLUETOOTH_State();

    // Timer
    if (++s == 200) {
      s = 0;
    }

    HAL_Delay(50);
    HAL_GPIO_TogglePin(led_GPIO_Port, led_Pin);
  }
  /* USER CODE END 3 */

}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{

  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;

    /**Initializes the CPU, AHB and APB busses clocks
    */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

    /**Initializes the CPU, AHB and APB busses clocks
    */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

    /**Configure the Systick interrupt time
    */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

    /**Configure the Systick
    */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}

/**
  * @brief NVIC Configuration.
  * @retval None
  */
static void MX_NVIC_Init(void)
{
  /* USART1_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(USART1_IRQn);
}

/* USER CODE BEGIN 4 */

void Flash_start(void) {
  if (FLASH_Read(0) != 0x55) {
    // Initial
    FLASH_Write(0, 0x55);

    // Record Minium Lightness Value ------MLV
    FLASH_Write(1, MINIUM_LIGHTNESS);

    // Record Door Open Threshold ---------DOT
    FLASH_Write(2, DOOR_OPEN_THRESHOLD);

    // Record Accel RH Threshold  ---------ART
    FLASH_Write(3, ACCEL_RH_THRESHOLD);

    FLASH_Write(4, colorR);
    FLASH_Write(5, colorG);
    FLASH_Write(6, colorB);

    FLASH_Write(7, colorR_Start);
    FLASH_Write(8, colorG_Start);
    FLASH_Write(9, colorB_Start);

    FLASH_Write(10, colorR_End);
    FLASH_Write(11, colorG_End);
    FLASH_Write(12, colorB_End);
  } else {
    MINIUM_LIGHTNESS = FLASH_Read(1);
    DOOR_OPEN_THRESHOLD = FLASH_Read(2);
    ACCEL_RH_THRESHOLD = FLASH_Read(3);

    colorR = FLASH_Read(4);
    colorG = FLASH_Read(5);
    colorB = FLASH_Read(6);

    colorR_Start = FLASH_Read(7);
    colorG_Start = FLASH_Read(8);
    colorB_Start = FLASH_Read(9);

    colorR_End = FLASH_Read(10);
    colorG_End = FLASH_Read(11);
    colorB_End = FLASH_Read(12);
  }
}

void FLASH_Write(uint8_t offset, uint16_t Flash_Val) {
  uint32_t address = FLASH_ADD + offset * 1024;

  FLASH_EraseInitTypeDef My_Flash;
  HAL_FLASH_Unlock();

  My_Flash.TypeErase = FLASH_TYPEERASE_PAGES;
  My_Flash.PageAddress = address;
  My_Flash.NbPages = 1;

  uint32_t PageError = 0;
  HAL_FLASHEx_Erase(&My_Flash, &PageError);

  HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, address, Flash_Val);

  HAL_FLASH_Lock();
}

uint16_t FLASH_Read(uint8_t offset) {
  uint32_t address = FLASH_ADD + offset * 1024;

  return *(__IO uint16_t*)( address );
}

void Door_Open(void) {
  WS2812B_flow(20);
}

void Door_Close(void) {
  WS2812B_DeInit(20);
}

void VL_show(void) {
  uint16_t distance_a, distance_b;
	static uint16_t distance_a_buff, distance_b_buff;
	
	// Block error return of 20
  distance_a = VL53L0X_A_Distance();
	if(distance_a == 20) {
		distance_a = distance_a_buff;
	} else {
		distance_a_buff = distance_a;
	}
	
  OLED_ShowChar(14, 2, distance_a / 100 % 10 + '0');
  OLED_ShowChar(15, 2, distance_a / 10 % 10 + '0');
  OLED_ShowChar(16, 2, distance_a % 10 + '0');

  HAL_Delay(50);
	
	// Block error return of 20
  distance_b = VL53L0X_B_Distance();
	if(distance_b == 20) {
		distance_b = distance_b_buff;
	} else {
		distance_b_buff = distance_b;
	}
	
  OLED_ShowChar(18, 2, distance_b / 100 % 10 + '0');
  OLED_ShowChar(19, 2, distance_b / 10 % 10 + '0');
  OLED_ShowChar(20, 2, distance_b % 10 + '0');

  // If no object stop laser, return 8190; If laser lost, return 0xffff
  if ((distance_a != 0xffff && distance_a > DOOR_OPEN_THRESHOLD) || (distance_b != 0xffff && distance_b > DOOR_OPEN_THRESHOLD)) {
    if (OPEN < 30) {
      OPEN++;
    }
  } else {
    if (OPEN > 0) {
      OPEN--;
    }
  }
}

void BMP_show(void) {
  int16_t T;
  uint32_t P;

  T = BMP280_Temp();
  P = BMP280_Pressure();

  if (T < 0) {
    T = -T;
    OLED_ShowChar(4, 0, '-');
    OLED_ShowChar(5, 0, T / 100 % 10 + '0');
    OLED_ShowChar(6, 0, '.');
    OLED_ShowChar(7, 0, T / 10 % 10 + '0');
    OLED_ShowChar(8, 0, T % 10 + '0');
  } else {
    OLED_ShowChar(4, 0, T / 1000 + '0');
    OLED_ShowChar(5, 0, T / 100 % 10 + '0');
    OLED_ShowChar(6, 0, '.');
    OLED_ShowChar(7, 0, T / 10 % 10 + '0');
    OLED_ShowChar(8, 0, T % 10 + '0');
  }

  OLED_ShowChar(13, 0, P / 100000 % 10 + '0');
  OLED_ShowChar(14, 0, P / 10000 % 10 + '0');
  OLED_ShowChar(15, 0, P / 1000 % 10 + '0');
  OLED_ShowChar(16, 0, P / 100 % 10 + '0');
  OLED_ShowChar(17, 0, P / 10 % 10 + '0');
  OLED_ShowChar(18, 0, P % 10 + '0');
}

void AP3212_show(void) {
  uint16_t ALS;

  uint8_t LIGHTNESS_RECORD[LIGHTNESS_RECORD_NUM] = {0x00};
  uint8_t LIGHTNESS_RECORD_COUNT = 0;
  uint16_t LIGHTNESS_RECORD_SUM = 0;
  uint8_t k = 0;

  ALS = AP3216_ALS();
  OLED_ShowChar(14, 1, ALS / 10000 % 10 + '0');
  OLED_ShowChar(15, 1, ALS / 1000 % 10 + '0');
  OLED_ShowChar(16, 1, ALS / 100 % 10 + '0');
  OLED_ShowChar(17, 1, ALS / 10 % 10 + '0');
  OLED_ShowChar(18, 1, ALS % 10 + '0');

  if (ALS > 255) {
    ALS = 255;
  } else if (ALS < MINIUM_LIGHTNESS) {
    ALS = MINIUM_LIGHTNESS;
  }

  LIGHTNESS_RECORD[k++] = ALS;
  if (k == LIGHTNESS_RECORD_NUM) {
    k = 0;
  }

  if (LIGHTNESS_RECORD_COUNT != LIGHTNESS_RECORD_NUM) {
    LIGHTNESS_RECORD_COUNT++;

    lightness = ALS;
  } else {
    for (uint8_t j = 0; j < ACCEL_RH_RECORD_NUM; j++) {
      LIGHTNESS_RECORD_SUM += LIGHTNESS_RECORD[j];
    }

    lightness = LIGHTNESS_RECORD_SUM / ACCEL_RH_RECORD_NUM;
  }
}

void MPU_show(void) {
  int16_t ACCEL_X, ACCEL_Y, ACCEL_Z;

  uint16_t ACCEL_RH, ACCEL_RH_DIFF;
  uint32_t ACCEL_RH_RECORD_SUM = 0;
  static uint16_t ACCEL_RH_ST = 0xffff;
  static uint16_t ACCEL_RH_RECORD[ACCEL_RH_RECORD_NUM] = {0x00};
  static uint8_t  ACCEL_RH_COUNT = 0;
  static uint8_t  k = 0;

  ACCEL_X = MPU6050_Single_Read(ACCEL_XOUT_H);
  ACCEL_X <<= 8;
  ACCEL_X |= MPU6050_Single_Read(ACCEL_XOUT_L);
  if (ACCEL_X < 0) {
    ACCEL_X = -ACCEL_X;
  }
  OLED_ShowChar(4, 1, ACCEL_X / 10000 % 10 + '0');
  OLED_ShowChar(5, 1, ACCEL_X / 1000 % 10 + '0');
  OLED_ShowChar(6, 1, ACCEL_X / 100 % 10 + '0');
  OLED_ShowChar(7, 1, ACCEL_X / 10 % 10 + '0');
  OLED_ShowChar(8, 1, ACCEL_X % 10 + '0');

  ACCEL_Y = MPU6050_Single_Read(ACCEL_YOUT_H);
  ACCEL_Y <<= 8;
  ACCEL_Y |= MPU6050_Single_Read(ACCEL_YOUT_L);
  if (ACCEL_Y < 0) {
    ACCEL_Y = -ACCEL_Y;
  }
  OLED_ShowChar(4, 2, ACCEL_Y / 10000 % 10 + '0');
  OLED_ShowChar(5, 2, ACCEL_Y / 1000 % 10 + '0');
  OLED_ShowChar(6, 2, ACCEL_Y / 100 % 10 + '0');
  OLED_ShowChar(7, 2, ACCEL_Y / 10 % 10 + '0');
  OLED_ShowChar(8, 2, ACCEL_Y % 10 + '0');

  ACCEL_Z = MPU6050_Single_Read(ACCEL_ZOUT_H);
  ACCEL_Z <<= 8;
  ACCEL_Z |= MPU6050_Single_Read(ACCEL_ZOUT_L);
  if (ACCEL_Z < 0) {
    ACCEL_Z = -ACCEL_Z;
  }
  OLED_ShowChar(4, 3, ACCEL_Z / 10000 % 10 + '0');
  OLED_ShowChar(5, 3, ACCEL_Z / 1000 % 10 + '0');
  OLED_ShowChar(6, 3, ACCEL_Z / 100 % 10 + '0');
  OLED_ShowChar(7, 3, ACCEL_Z / 10 % 10 + '0');
  OLED_ShowChar(8, 3, ACCEL_Z % 10 + '0');

  ACCEL_RH = sqrt((ACCEL_X * ACCEL_X)*0.3 + (ACCEL_Y * ACCEL_Y)*0.6 + (ACCEL_Z * ACCEL_Z)*0.1);
  OLED_ShowChar(14, 3, ACCEL_RH / 10000 % 10 + '0');
  OLED_ShowChar(15, 3, ACCEL_RH / 1000 % 10 + '0');
  OLED_ShowChar(16, 3, ACCEL_RH / 100 % 10 + '0');
  OLED_ShowChar(17, 3, ACCEL_RH / 10 % 10 + '0');
  OLED_ShowChar(18, 3, ACCEL_RH % 10 + '0');

  // Set Standard ACCEL_RH
  if (ACCEL_RH_ST == 0xffff) {
    ACCEL_RH_ST = ACCEL_RH;
    ACCEL_RH_DIFF = ACCEL_RH_THRESHOLD;
  } else {
    if (ACCEL_RH > ACCEL_RH_ST) {
      ACCEL_RH_DIFF = ACCEL_RH - ACCEL_RH_ST;
    } else {
      ACCEL_RH_DIFF = ACCEL_RH_ST - ACCEL_RH;
    }
  }

  if (ACCEL_RH_DIFF > ACCEL_RH_THRESHOLD) {
    WS2812B_Blink(80);
  } else {
    ACCEL_RH_RECORD[k++] = ACCEL_RH;

    if (k == ACCEL_RH_RECORD_NUM) {
      k = 0;
    }

    if (ACCEL_RH_COUNT != ACCEL_RH_RECORD_NUM) {
      ACCEL_RH_COUNT++;
    } else {
      for (uint8_t j = 0; j < ACCEL_RH_RECORD_NUM; j++) {
        ACCEL_RH_RECORD_SUM += ACCEL_RH_RECORD[j];
      }
      ACCEL_RH_ST = ACCEL_RH_RECORD_SUM / ACCEL_RH_RECORD_NUM;
    }
  }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  file: The file name as string.
  * @param  line: The line in file as a number.
  * @retval None
  */
void _Error_Handler(char *file, int line)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
